/*
 * @Author: Zhouhai 497675647@qq.com
 * @Date: 2022-11-08 17:43:31
 * @LastEditors: Zhouhai 497675647@qq.com
 * @LastEditTime: 2022-11-09 10:16:21
 */
import hljs from 'highlight.js';
import { CopyToClipboard } from 'react-copy-to-clipboard';
import 'highlight.js/styles/vs.css';
import xml from 'highlight.js/lib/languages/xml';
import java from 'highlight.js/lib/languages/java';
import javascript from 'highlight.js/lib/languages/javascript';
import sql from 'highlight.js/lib/languages/sql';
import { useEffect } from 'react';
import { Button, message } from 'antd';
import { CopyOutlined } from '@ant-design/icons';

export type HighlightProps = {
    language: string;
    content: string;
}
const Highlight: React.FC<HighlightProps> = ({language, content}) => {
    hljs.registerLanguage("java", java);
    hljs.registerLanguage("xml", xml);
    hljs.registerLanguage("html", xml);
    hljs.registerLanguage("vue", xml);
    hljs.registerLanguage("react", xml);
    hljs.registerLanguage("d.ts", javascript);
    hljs.registerLanguage("ts", javascript);
    hljs.registerLanguage("tsx", javascript);
    hljs.registerLanguage("javascript", javascript);
    hljs.registerLanguage("sql", sql);

    useEffect(() => {
        // 配置 highlight.js
        hljs.configure({
            // 忽略未经转义的 HTML 字符
            ignoreUnescapedHTML: true,
        });
    }, []);

    const renderhighlightedCode = () => {
        const result = hljs.highlight(language, content || "", true);

        return `<pre><code>${result.value}</code></pre>`;
    }
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    const onCopy = (_text: string, _result: boolean) => {
        message.success('复制成功！');
    }

    return (
        <div className="dg-html">
            <div style={{ float: "right", paddingRight: "5px" }}>
                <CopyToClipboard text={content} onCopy={onCopy}>
                    <Button size='small'><CopyOutlined />Copy</Button>
                </CopyToClipboard>
            </div>
            <div dangerouslySetInnerHTML={{ __html: renderhighlightedCode() }} />
        </div>
    );
}

export default Highlight;